<?php

declare (strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use think\facade\Db;
use think\facade\View;
use think\facade\Request;
use think\facade\Cookie;
use app\model\User as UserModel;
use app\model\UserGroup as GroupModel;
use app\model\Log;
use app\validate\User as ValidateUser;
use think\exception\ValidateException;

class User extends Common
{
    public function index($act = null, $uid = 0)
    {
        if ($act == 'edit') {
            $uid = intval($uid);
            $userinfo = UserModel::find($uid);
            if (!$userinfo) {
                return error(lang('参数错误'));
            }
            View::assign('userinfo', $userinfo);

            $group = GroupModel::field('id,title')->where(['status' => 1])->select();
            View::assign('group', $group);

            return View::fetch('form');
        }

        if ($act == 'add') {
            $group = GroupModel::field('id,title')->where(['status' => 1])->select();
            View::assign('group', $group);
            return View::fetch('form');
        }

        if ($act == 'update') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $uid = intval($uid);
            $data = input('post.');
            $data['birthday'] = strtotime($data['birthday']);
            if (!isset($data['status'])) {
                $data['status'] = 0;
            }
            if (Db::name('user')->where(['uid' => $uid])->count() == 0) {//新增
                if ($data['username'] == '') {
                    return error(lang('用户名不能为空'));
                }
                if ($data['password'] == '') {
                    return error(lang('密码不能为空'));
                }
                if (Db::name('user')->where(['username' => $data['username']])->count() > 0) {
                    return error(lang('用户名已被占用，请重试'));
                }

                $data['password'] = password($data['password']);
                $r = Db::name('user')->insert($data);
                if ($r) {
                    add_log('新增用户，用户名：'.$data['username'], $this->request->user->username);
                    return success(lang('操作成功'), (string) url('admin/user/index'));
                }
            } else {//编辑
                if ($data['password'] == '') {
                    unset($data['password']);
                } else {
                    $data['password'] = password($data['password']);
                }
                $r = Db::name('user')->where(['uid' => $uid])->update($data);
                if ($r) {
                    add_log('修改用户信息，UID：'.$uid, $this->request->user->username);
                    return success(lang('操作成功'), (string) url('admin/user/index'));
                }
            }
            return error(lang('参数错误'));
        }

        if ($act == 'del') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $uids = input('post.');
            if (empty($uids)) {
                return error(lang('请勾选需要删除的选项'));
            }
            $uids = $uids['uids'];
            $r = Db::name('user')->delete($uids);
            if ($r) {
                add_log('删除用户，UID：'.implode(',', $uids), $this->request->user->username);
                return error(lang('操作成功'), (string) url('admin/user/index'));
            } else {
                return error(lang('请勾选需要删除的选项'));
            }
        }

        $list = Db::name('user')
                ->alias('u')
                ->join('user_group g', 'g.id=u.ugid', 'left')
                ->field('u.uid,u.ugid,u.username,u.status,u.sex,u.birthday,u.tel,u.qq,u.email,g.title')
                ->order('u.uid desc')
                ->paginate(25);

        View::assign('list', $list);
        return View::fetch();
    }

    public function login()
    {
        if ($this->request->method() == 'POST') {
            $data = $this->request->post();
            $validate = new ValidateUser();
            if (!$validate->check($data)) {
                return json(['code' => 0,'msg' => $validate->getError(),'data' => []]);
            }

            if (!captcha_check($data['captcha'])) {
                return json(['code' => 0,'msg' => lang('验证码错误'),'data' => []]);
            };

            $user = UserModel::where(['username' => $data['username'],'password' => password($data['password'])])->find();
            if (!$user) {
                add_log('用户或密码错误', $data['username']);
                return json(['code' => 0,'msg' => lang('用户或密码错误'),'data' => []]);
            }
            if ($user->status === 0) {
                return json(['code' => 0,'msg' => lang('用户已被禁用'),'data' => []]);
            }
            if ($user->group->status === 0) {
                return json(['code' => 0,'msg' => lang('用户组已被禁用'),'data' => []]);
            }

            $token = password(uniqid((string) rand(), true));
            $salt = random(10);
            $identifier = password($user['uid']. md5($user['username'] . $salt));
            $auth = $identifier.$token;

            $user->identifier = $identifier;
            $user->token = $token;
            $user->salt = $salt;
            $user->save();

            if (isset($data['remember'])) {
                Cookie::set('auth', $auth, 3600 * 24 * 365);
            } else {
                Cookie::set('auth', $auth);
            }
            add_log('登录成功', $user->username);
            return json(['code' => 1, 'msg' => lang('操作成功'),'data' => []]);
        }


        return View::fetch();
    }

    public function profile()
    {
        if (Request::isPost()) {
            $data = input('post.');
            $data['birthday'] = $data['birthday'] == '' ? time() : strtotime($data['birthday']);
            if ($data['password'] == '') {
                unset($data['password']);
            } else {
                $data['password'] = password($data['password']);
            }

            $this->request->user->save($data);
            add_log('修改个人资料，ID：'.$this->request->user->uid, $this->request->user->username);
            return  success(lang('操作成功'), (string) url('admin/user/profile'));
        }
        return View::fetch();
    }
    public function logout()
    {
        Cookie::delete('auth');
        return redirect((string) url('admin/user/login'));
    }

    public function skin()
    {
        $skin = input('get.skin');
        $this->request->user->skin = $skin;
        $this->request->user->save();
        return json($this->request->user);
    }
}
